package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
     private OrdersMapper ordersMapper;
    @Autowired
     private OrdersService ordersService;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {
        log.info("处理支付超时订单:{}", LocalDateTime.now());
        //查询订单是否为待付款
        List<Orders> count = ordersMapper.countStatus(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (count==null || count.size()==0){
            return;
        }
        for (Orders orders : count) {
            //更新订单状态
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Orders::getId,orders.getId())
                    .set(Orders::getStatus,Orders.CANCELLED)
                    .set(Orders::getCancelReason,"支付超时")
                    .set(Orders::getCancelTime,LocalDateTime.now());
            ordersService.update(updateWrapper);
        }

    }
    /**
     * 处理处于待派送状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder() {
        log.info("处理处于待派送状态的订单:{}", LocalDateTime.now());
        //查询订单是否为待派送状态
        List<Orders> count = ordersMapper.countStatus(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-60));
        if (count==null || count.size()==0){
            return;
        }
        for (Orders orders : count) {
            //更新订单状态
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Orders::getId,orders.getId())
                    .set(Orders::getStatus,Orders.COMPLETED);
                    ordersService.update(updateWrapper);
                    log.info("更新订单状态成功:{}",orders.getId());
        }
    }
}
